<?php

namespace App\Api\Three\ShopA;

/**
 * https://docs.qq.com/doc/DRUlEamNJWFFhVmVR
 */

use App\Api\ChannelApi;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;

// use function GuzzleHttp\json_decode;
//  湖南电信接口
class HuNanTelecom extends ChannelApi
{
    protected $model;
    protected $appKey = '';
    protected $url = '';
    protected $secret = '';
    protected $channel = '';
    protected $config = [];
    protected $HTTPOK = 1; //检查接口返回的数据 返回1 代表返回正确
    protected $root;
    protected $log;
    protected $isTrue = true;
    protected $return_message = '';
    protected $accessToken;
    protected $pname;
    protected $source;
    protected $ordersource;

    public function __construct($url = '', $str = '')
    {
        // 南沙
        $this->pname = 'HuNanTelecom';
        $this->log = new Logger('HuNanTelecom');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/HuNanTelecom.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $params = strToKeyValArr($str);
        $this->url = $url;
        $this->source = $params['source'];
        $this->ordersource = $params['ordersource'];
        $this->accessToken = !empty($params['access_token']) ? $params['access_token'] : 'M2EzMzRhYWM1ZmY5YThlNWEyNjI2N2Y2MDhlY2Q5MDA=';
    }
    public function sentPost($method, $data)
    {
        $data = [
            'access_token' => $this->accessToken,
            'content' => $data,
            'method' => ((string)$method),
            'version' => (string)"1.0"
        ];
        // var_dump($data);
        $headers = [
            'application/json; charset=UTF-8',
        ];
        $res = $this->sendBefare($this->url, $data, $headers);
        return $res;
    }
    public function selectNumber($array = [])
    {
        $method = 'qry.nmall.phoneNumberlList';
        $data = [
            'data' => [
                'poolId' => '1356',
                'areaCode' => '731',
                'currentPage' => "1",
                'isMain' => '1',
                'pageSize' => '10',
                'regionRange' => "001",
            ],
            'apiName' => 'num.accept.normalList',
            'channel' => 'qqtxqd',
            'timestamp' => time(),
        ];
        // var_dump($data, 111111111);
        $data['sign'] = $this->getSign($data);
        // ksort($data);
        $res =  $this->sentPost($method, $data);
        var_dump($res, 44444);
        return $res;
    }
    public function checkOrder($array = [])
    {
        $method = 'chk.ordercheck.InternetCardQualifica';
        $data = [
            'cartNo' => $array['pay_identity'],
            'serviceOrderSource' => $this->source,
            'serviceOrderSalesNumber' => $array['channel_code'],
            'buyerName' => $array['pay_name'],
            'mobilePhone' => $array['pay_phone'],
            'receiverName' => $array['pay_name'],
            'receiverProv' => $array['post_province'],
            'receiverCity' => $array['post_city'],
            'receiverDistrict' => $array['post_area'],
            'receiverAdress' => $array['post_address']
        ];
        $res = $this->sentPost($method, $data);
        // var_dump($res);
        if (is_string($res)) {
            $res = json_decode($res, true);
        }
        if (isset($res['res_code']) && $res['res_code'] == '00000') {
            if (!empty($res['result'])) {
                $result = $res['result'];
                if (isset($result['code']) && $result['code'] === 0) {
                    return $this->returnMsg(200, !empty($result['message']) ? $result['message'] : '暂不能办理', ['msg' => !empty($result['message']) ? $result['message'] : '暂不能办理']);
                }
                return $this->returnMsg(101, !empty($result['message']) ? $result['message'] : '接口调用失败', ['msg' => !empty($result['message']) ? $result['message'] : '接口调用失败']);
            }
            return $this->returnMsg(101, !empty($res['res_message']) ? $res['res_message'] : '接口调用失败', ['msg' => !empty($res['res_message']) ? $res['res_message'] : '接口调用失败']);
        }
        return $this->returnMsg(101, !empty($res['res_message']) ? $res['res_message'] : '应用调用失败', ['msg' => !empty($res['res_message']) ? $res['res_message'] : '应用调用失败']);
    }
    public  function getStatusCode($status, $arrsy = [])
    {
        $str = 'qita@qita@qiaoqiao';
        $strs = 'qiaoqiao01';
        if (!empty($arrsy['dist_name'])) {
            switch ($arrsy['dist_name']) {
                case '乔乔通信':
                    $strs = 'qiaoqiao02';
                    break;
                case '玖叁通信':
                    $strs = 'sanjiu01';
                    break;
                case '壹捌壹通信':
                    $strs = 'yibieyi01';
                    break;
            }
        }

        switch ($status) {
            case 1:
                $str = 'zb@dy@' . $strs;
                break;
            case 6:
                $str = 'zb@dy@' . $strs;
                break;
        }
        return $str;
    }
    // 提交上游
    public function orderSubmit($array = [])
    {
        // // 暂时先不发送 返回成功

        // 组装提交数据
        $method = 'syn.orderinfo.SynJdServiceOrder';
        $time = date('Y-m-d H:i:s');
        $getStatusCode = $this->getStatusCode(!empty($array['source']) ? $array['source'] : '');
        $array['orderno'] = str_replace("HK_", '', $array['orderno']);
        $data = [
            'serviceOrderOutOrderId' => $array['orderno'],
            'serviceOrderSubmitTime' => $time,
            'serviceOrderCusName' => $array['pay_name'],
            'serviceOrderCusCardNo' => $array['pay_identity'],
            'serviceOrderCusContactPhone' => $array['pay_phone'],
            'serviceOrderSalesNumber' => $array['channel_code'],
            'serviceOrderReceiverName' => $array['pay_name'],
            'serviceOrderReceiverProvCode' => $array['post_province'],
            'serviceOrderReceiverCityCode' => $array['post_city'],
            'serviceOrderReceiverDistrictCode' => $array['post_area'],
            'serviceOrderReceiverAddress' => $array['post_address'],
            'serviceOrderType' => 'hlwkzdhdd', // 订单业务类型
            'serviceOrderSource' => $this->ordersource, // 订单渠道
            'serviceOrderCpsRefereePeople' => $getStatusCode,
            'serviceOrderRefereePeople' => 'CPS2',
            'serviceOrderIccid' => ''
        ];
        $res = $this->sentPost($method, $data);
        // var_dump($res);
        if (is_string($res)) {
            $res = json_decode($res, true);
        }
        if (isset($res['res_code']) && $res['res_code'] == '00000') {
            if (!empty($res['result'])) {
                $result = $res['result'];
                if (isset($result['code']) && $result['code'] === 0) {
                    return $this->returnMsg(200, !empty($result['message']) ? $result['message'] : '验权成功', ['msg' => !empty($result['message']) ? $result['message'] : '验权成功']);
                }
                return $this->returnMsg(101, !empty($result['message']) ? $result['message'] : '接口调用失败', ['msg' => !empty($result['message']) ? $result['message'] : '接口调用失败']);
            }
            return $this->returnMsg(101, !empty($res['res_message']) ? $res['res_message'] : '接口调用失败', ['msg' => !empty($res['res_message']) ? $res['res_message'] : '接口调用失败']);
        }
        return $this->returnMsg(101, !empty($res['res_message']) ? $res['res_message'] : '应用调用失败', ['msg' => !empty($res['res_message']) ? $res['res_message'] : '应用调用失败']);
        if (!empty($res)) {
            return $this->returnMsg(200, '提交成功', ['order_id' => !empty($res) ? $res : '']);
        }
        return $this->returnMsg(100, '提交失败', ['order_id' => !empty($res) ? $res : '']);
    }
    // 不同套餐 设置的参数不一样
    public function setData($data)
    {
    }
    // 查询订单 查询
    public function queryOrderStatus($array = [])
    {
    }
    // 处理数据 将数据处理成统一格式
    public function queryOneOrder($array = [])
    {
        $res = $this->queryOrderStatus($array);
        if (empty($res['data'])) {
            return $this->returnMsg(100, '数据为空');
        }
        if (empty($res['data']['data']['q'])) {
            return $this->returnMsg(101, '未查询到数据');
        }
        $getData = $res['data']['data']['q'][0];
        $data = [
            'id' => $getData['uid'],
            'sup_order' => $getData['订单编码'],
            'created_at' => date('Y-m-d H:i:s', strtotime($getData['下单时间'])),
            'order_desc' => $getData['订单当前状态']['订单状态名称'],
            'order_desc_at' => date('Y-m-d H:i:s', strtotime($getData['订单当前状态']['订单当前状态|状态更新时间'])),
            'order_num' => $getData['订单来源2']['订单来源单号'],
            'pagename' => $getData['订购产品']['产品名称'],
            'express_company' => $getData['订单配送方式']['配送公司'],
            'express_number' => !empty($getData['订单配送方式']['配送公司']) ? $getData['订单配送方式']['配送公司'] : '',
            'province' => !empty($getData['收件人地址'][0]['省']) ? $getData['收件人地址'][0]['省'] : '',
            'city' => !empty($getData['收件人地址'][0]['市']) ? $getData['收件人地址'][0]['市'] : '',
            'area' => !empty($getData['收件人地址'][0]['区']) ? $getData['收件人地址'][0]['区'] : '',
            'address' => !empty($getData['收件人地址'][0]['详细地址']) ? $getData['收件人地址'][0]['详细地址'] : '',
        ];
        return $this->returnMsg(200, '查询成功', [$data]);
    }
    public function sendBefare($url, $data)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        $this->log->info('湖南电信参数:' . json_encode($data) . '返回参数:' . $response);
        curl_close($curl);
        return $response;
    }
    public function sendBefare_back($url, $data, $headers, $isPost = 1)
    {
        // return 1212222222222;
        $curl = curl_init(); // 启动一个CURL会话
        if (!empty($isPost)) {
            // $url = $url . '?' . http_build_query($data);
        }
        var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if ($isPost == 1) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包 http_build_query
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        if (curl_error($curl)) {
            //请求失败，返回错误信息
            $res =  curl_error($curl);
            var_dump($res);
            return $res;
        }
        curl_close($curl); // 关闭CURL会话
        $this->log->info('湖南电信参数:' . json_encode($data) . '返回参数:' . $result);
        return $result;
    }
    public function sendBefareGet($url, $data, $headers)
    {
        $curl = curl_init(); // 启动一个CURL会话
        $url = $url . '?data=' . urlencode($data);
        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        // var_dump($result, 111111111);
        curl_close($curl); // 关闭CURL会话
        return $result;
    }
    public function getSign($params)
    {
        ksort($params);
        $arr = array_filter($params);
        $str = '';
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                $str .= $k . json_encode($v);
            } else {
                $str .= $k . $v;
            }
        }
        $b = $str . '&secret=32959021a5c6d23d13249aafdfb22c80';
        return md5($b);
    }
    public function getSign_back($str)
    {
        if (is_array($str)) {
            $str = json_encode($str, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }
        $strs = strtolower(md5($str));
        $getPKey = $this->getPublicKey();
        $key = openssl_pkey_get_public($getPKey);
        $return = openssl_public_encrypt($strs, $crypted, $key);
        if (!$return) {
            return '';
        }
        return base64_encode($crypted);
    }
    public function getPublicKey()
    {
        return '';
    }
}
